package com.boxuegu.websecurity.bbs.filter;

import org.owasp.validator.html.*;

/**
 * @program: cyberDefense
 * @description: 使用 owasp的 antiSamy 预防XSS过滤
 *
 * *  依赖：
 *  *   <dependency>
 *  *         <groupId>org.owasp.antisamy</groupId>
 *  *         <artifactId>antisamy</artifactId>
 *  *         <version>1.5.8</version>
 *  *   </dependency>
 *
 * @author: fengjd
 * @create: 2022-07-27 13:37
 **/
public class XSSEncode2 {
    private static Policy policy = null;

    static {
        String path = XSSEncode2.class.getClassLoader().getResource("antisamy-anythinggoes.xml").getFile();
        System.out.println("policy_filepath:" + path);
        if (path.startsWith("file")) {
            path = path.substring(6);
        }
        try {
            policy = Policy.getInstance(path);
        } catch (PolicyException e) {
            e.printStackTrace();
        }
    }

    public static String xssEncode(String value) {
        AntiSamy antiSamy = new AntiSamy();
        try {
            final CleanResults cr = antiSamy.scan(value, policy);
            // 安全的HTML输出
            return cr.getCleanHTML();
        } catch (ScanException e) {
            e.printStackTrace();
        } catch (PolicyException e) {
            e.printStackTrace();
        }
        return value;
    }
}
